package main

import (
	"fmt"
	"net"
	"time"
)

type deviceServer struct {
	id       string
	addr     *net.TCPAddr
	listener *net.TCPListener
	conns    map[string]net.Conn
	terminal bool
}

func (s *deviceServer) start(port string) {
	var err error
	s.terminal = false
	s.addr, err = net.ResolveTCPAddr("tcp", port)
	checkError(err)
	listener, err := net.ListenTCP("tcp", s.addr)
	checkError(err)
	fmt.Println(s.id + ":listener")
	s.listener = listener
	s.conns = make(map[string]net.Conn)
	go s.run(listener)
}
func (s *deviceServer) run(listener *net.TCPListener) {
	if listener == nil {
		return
	}
	i := 0
	for {
		conn, err := listener.Accept()
		fmt.Println("conn  ")
		if s.terminal {
			return
		}
		if err != nil {
			continue
		}
		i++
		thisTime := mytime()
		fmt.Println(s.id+":new request", i, " from ", conn.RemoteAddr(), "  return time", thisTime)
		go func() {
			var mybuff [512]byte
			conn.SetReadDeadline(time.Now().Add(10000 * time.Millisecond))
			n, err := conn.Read(mybuff[0:])
			if err != nil {
				fmt.Println("Must be read data,but nothing!!!")
				conn.Close()
			}
			fmt.Println("read byte:", n)
			fmt.Println(mybuff[0:n])
			s.conns[string(mybuff[0:n])] = conn
		}()

	}
}
func (s *deviceServer) stop() {
	s.terminal = true
	for _, v := range s.conns {
		v.Close()
	}
	if s.listener != nil {
		s.listener.Close()
	}
}

func (s *deviceServer) transmit(data []byte) {
	var separator byte

	var devid string
	var cmd []byte
	//parse id
	separator = ','
	for n, v := range data {
		if v == separator {
			devid = string(data[0:n])
			cmd = data[n+1:]
			break
		}
	}
	if len(devid) < 1 {
		fmt.Println("Cann't parse devid")
		return
	}
	fmt.Println("devid:", devid, " cmd:", cmd)
	conn := s.conns[devid]
	if conn == nil {
		fmt.Println("mismatch conn to devid:", devid)
		return
	}
	conn.SetWriteDeadline(time.Now().Add(15000 * time.Millisecond))
	conn.Write(cmd)
}
